﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleCalc
{
    class Calculator
    {
        IList<object> equation;
        double currentValue;
        Operation nextOperation;
        bool NumericAlreadyEnqueued;

        public Calculator()
        {
            equation = new List<object>();
            currentValue = 0;
            nextOperation = null;
            NumericAlreadyEnqueued = false;
            LastNumeric = "";
        }

        internal void Compute()
        {
            if (!NumericAlreadyEnqueued)
            {
                currentValue = nextOperation.Perform(currentValue, Double.Parse(LastNumeric));
            }

            LastNumeric = currentValue.ToString();
            equation.Clear();
            nextOperation = null;
            NumericAlreadyEnqueued = false;

        }

        internal void Backspace()
        {
            if (LastNumeric.Length > 0)
            {
                LastNumeric = LastNumeric.Substring(0, LastNumeric.Length - 1);
            }
        }

        internal void AddOperator(Operation op)
        {
            if (!NumericAlreadyEnqueued)
            {
                NumericAlreadyEnqueued = true;

                equation.Add(Double.Parse(LastNumeric));
                if (nextOperation == null)
                {
                    currentValue = Double.Parse(LastNumeric);
                }
                else
                {
                    currentValue = nextOperation.Perform(currentValue, Double.Parse(LastNumeric));
                }
            }
            else
            {
                equation.RemoveAt(equation.Count - 1);
            }
            equation.Add(op);
            nextOperation = op;
        }

        internal void AddDigit(int p)
        {
            if (NumericAlreadyEnqueued)
            {
                LastNumeric = p.ToString();
            }
            else
            {
                LastNumeric += p.ToString();
            }
            NumericAlreadyEnqueued = false;
        }

        public String CurrentEquation { get {
            StringBuilder buf = new StringBuilder();
            foreach (object obj in equation)
                buf.Append(obj.ToString()).Append(" ");
            return buf.ToString(); 
        } }

        public String LastNumeric { get; private set; }

        internal void Clear()
        {
            equation.Clear();
            currentValue = 0;
            nextOperation = null;
            NumericAlreadyEnqueued = false;
            LastNumeric = "";
        }
    }
}
